package com.hcrazy.manchester.app.jdbc;

import java.util.ArrayList;
import java.util.List;

import com.hcrazy.manchester.app.pojo.Advert;
import com.hcrazy.manchester.app.pojo.PageModel;
import com.hcrazy.manchester.app.pojo.Topic;
import com.hcrazy.manchester.app.utils.Constant;

public class TopicDAO extends BaseDAO<Topic>{

	/**
	 * 发表主题
	 * @param topic
	 * @throws Exception
	 */
	public long addTopic(Topic topic) throws Exception{
		StringBuffer sb = new StringBuffer();
		sb.append("insert into him_forum_topic(");
		sb.append("forumId,author,authorId,subject,postDate,message,userIp,lastPost,lastPoster,type,images,");
		sb.append("closed,members,appointTime,appointDemand,joinType,viewPerm,linkMan,linkPhone,inviteUsers,appointType,praiseBaseCount,praiseCount,commentBaseCount,commentCount");
		sb.append(") values (");
		sb.append(":forumId,:author,:authorId,:subject,:postDate,:message,:userIp,:lastPost,:lastPoster,:type,:images,");
		sb.append(":closed,:members,:appointTime,:appointDemand,:joinType,:viewPerm,:linkMan,:linkPhone,:inviteUsers,:appointType,:praiseBaseCount,:praiseCount,:commentBaseCount,:commentCount");
		sb.append(")");
		
		update(sb.toString(), topic);
		
		return getIncreamentId();
	}
	
	/**
	 * 编辑主题
	 * @param topic
	 * @throws Exception
	 */
	public void updateTopic(Topic topic) throws Exception{
		StringBuffer sb = new StringBuffer();
		sb.append("update him_forum_topic set ");
		sb.append(" forumId=:forumId,subject=:subject,message=:message,lastPost=:lastPost,images=:images,views=:views,replies=:replies,");
		sb.append("closed=:closed,members=:members,appointTime=:appointTime,appointDemand=:appointDemand,joinType=:joinType,viewPerm=:viewPerm,linkMan=:linkMan,linkPhone=:linkPhone,inviteUsers=:inviteUsers,appointType=:appointType,");
		sb.append(" praiseBaseCount=:praiseBaseCount,praiseCount=:praiseCount,commentBaseCount=:commentBaseCount,commentCount=:commentCount");
		sb.append(" where topicId = :topicId");
		
		update(sb.toString(), topic);
	}
	
	/**
	 * 主题列表（客户端功能）
	 * @param model
	 * @param type
	 * @param forumId
	 * @return
	 * @throws Exception
	 */
	public PageModel getPagedInfos(PageModel model,int typeMode,int forumId,int type) throws Exception{
		StringBuilder querySQL = new StringBuilder("select * from (select a.*,b.header from him_forum_topic a,him_user_info b where a.authorId = b.userId) c");
		StringBuilder countSQL = new StringBuilder("select count(*) from (select a.*,b.header from him_forum_topic a,him_user_info b where a.authorId = b.userId) c ");
		StringBuilder whereSQL = new StringBuilder(" where type = ? ");
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(type);
		
		if(forumId > 0){
			whereSQL.append(" and forumId = ?");
			paramList.add(forumId);
		}
		if(typeMode == Constant.TOPIC_DISPLAY_TYPE_0){
			//最新发表
			whereSQL.append(" order by postDate desc");
		}else if(typeMode == Constant.TOPIC_DISPLAY_TYPE_1){
			//最新回复
			whereSQL.append(" order by lastPost desc");
		}else if(typeMode == Constant.TOPIC_DISPLAY_TYPE_2){
			//精华帖子
			whereSQL.append(" order by digest desc, lastPost desc");
		}else if(typeMode == Constant.TOPIC_DISPLAY_TYPE_3){
			//置顶帖子
			whereSQL.append(" order by displayOrder desc, lastPost desc");
		}
		
		return this.getPageModel(model, querySQL, countSQL, whereSQL, paramList, Topic.class);
	}
	
	/**
	 * 获取最热帖子
	 * @param size
	 * @param type
	 * @return
	 * @throws Exception
	 */
	public List<Topic> getHotTopics(int size,int type) throws Exception{
		String sql = "select * from him_forum_topic where type = ? order by replies desc limit ?";
		return this.getList(sql, Topic.class,type,size);
	}
	
	/**
	 * 我发表的主题列表（客户端功能）
	 * @param model
	 * @param authorId
	 * @return
	 * @throws Exception
	 */
	public PageModel getMyTopics(PageModel model,long authorId) throws Exception{
		StringBuilder querySQL = new StringBuilder("select c.* from (select a.*,b.`name`,m.header from him_forum_topic a,him_forum_forum b,him_user_info m where a.forumId = b.forumId and a.authorId = m.userId ) as c ");
		StringBuilder countSQL = new StringBuilder("select count(*) from (select a.*,b.`name`,m.header from him_forum_topic a,him_forum_forum b,him_user_info m where a.forumId = b.forumId and a.authorId = m.userId ) as c");
		StringBuilder whereSQL = new StringBuilder(" where authorId = ? ");
		//最新发表
		whereSQL.append(" order by postDate desc");
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(authorId);
		
		return this.getPageModel(model, querySQL, countSQL, whereSQL, paramList, Topic.class);
	}
	
	/**
	 * 同城主题列表（客户端功能）
	 * @param model
	 * @param authorId
	 * @return
	 * @throws Exception
	 */
	public PageModel getTopicsByCityId(PageModel model,int cityId) throws Exception{
		StringBuilder querySQL = new StringBuilder("select c.* from (select a.*,b.`name`,m.header,m.cityId from him_forum_topic a,him_forum_forum b,him_user_info m where a.forumId = b.forumId and a.authorId = m.userId ) as c ");
		StringBuilder countSQL = new StringBuilder("select count(*) from (select a.*,b.`name`,m.header,m.cityId from him_forum_topic a,him_forum_forum b,him_user_info m where a.forumId = b.forumId and a.authorId = m.userId ) as c");
		StringBuilder whereSQL = new StringBuilder(" where cityId = ? ");
		//最新发表
		whereSQL.append(" order by postDate desc");
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(cityId);
		
		return this.getPageModel(model, querySQL, countSQL, whereSQL, paramList, Topic.class);
	}
	
	/**
	 * 后台功能
	 * @param model
	 * @param forumId
	 * @param authors
	 * @param title
	 * @param startTime
	 * @param endTime
	 * @return
	 * @throws Exception
	 */
	public PageModel getPagedInfos(PageModel model,int forumId,String authors,String title,long startTime,long endTime,int type,int sortId) throws Exception{
		StringBuilder querySQL = new StringBuilder("select * from (select a.*,b.name,b.sortId from him_forum_topic a,him_forum_forum b where a.forumId = b.forumId and ((b.type <> 0 and b.`status` <> 2) or b.`status` = 2)) as c ");
		StringBuilder countSQL = new StringBuilder("select count(*) from (select a.*,b.name,b.sortId from him_forum_topic a,him_forum_forum b where a.forumId = b.forumId and ((b.type <> 0 and b.`status` <> 2) or b.`status` = 2)) as c ");
		StringBuilder whereSQL = new StringBuilder(" where subject like ? and type = ? ");
		
		if(forumId == 2){
			querySQL = new StringBuilder("select * from (select a.*,b.name,b.sortId,ab.menuName from him_forum_topic a,him_forum_forum b,him_book_menu ab where a.appointType = ab.menuId and a.forumId = b.forumId and ((b.type <> 0 and b.`status` <> 2) or b.`status` = 2)) as c ");
			countSQL = new StringBuilder("select count(*) from (select a.*,b.name,b.sortId,ab.menuName from him_forum_topic a,him_forum_forum b,him_book_menu ab where a.appointType = ab.menuId and a.forumId = b.forumId and ((b.type <> 0 and b.`status` <> 2) or b.`status` = 2)) as c ");
		}
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.add("%" + title + "%");
		paramList.add(type);
		
		if(forumId > 0){
			whereSQL.append(" and forumId = ? ");
			paramList.add(forumId);
		}else{
			whereSQL.append(" and forumId <> 2 ");//去掉约
		}
		
		if(sortId > 0){
			whereSQL.append(" and sortId = ? ");
			paramList.add(sortId);
		}
		
		if(null != authors && !"".equals(authors)){
			String[] authorList = authors.split(",");
			whereSQL.append(" and ( author = ?");
			paramList.add(authorList[0]);
			if(authorList.length > 0){
				for(int i=1;i<authorList.length;i++){
					whereSQL.append(" or author = ? ");
					paramList.add(authorList[i]);
				}
			}
			whereSQL.append(" ) ");
		}
		
		if(startTime > 0 && endTime > 0 ){
			whereSQL.append(" and ( postDate > ? and postDate < ? )");
			paramList.add(startTime);
			paramList.add(endTime);
		}
		
		whereSQL.append(" order by c.lastPost desc");
		
		System.out.println(querySQL.toString()+whereSQL.toString());
		System.out.println(paramList);
		
		return this.getPageModel(model, querySQL, countSQL, whereSQL, paramList, Topic.class);
	}
	
	public int getIncreamentId() throws Exception {
		String sql = "select LAST_INSERT_ID() id from him_forum_topic limit 0,1 ";
		
		return this.getJdbcTemplate().queryForInt(sql);
	}
	
	/**
	 * 批量移动到目标版块
	 * @param topicIds
	 * @param forumId
	 * @throws Exception
	 */
	public void batchMoveForum(String[] topicIds,int forumId) throws Exception{
		String sql = "update him_forum_topic set forumId = ? where topicId = ?";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		
		for(String topicId:topicIds){
			Object[] args = new Object[]{forumId,topicId};
			batchArgs.add(args);
		}
		this.getJdbcTemplate().batchUpdate(sql, batchArgs);
	}
	
	/**
	 * 批量置顶
	 * @param topics
	 * @param upOption
	 * @throws Exception
	 */
	public void batchSetTopicUp(String[] topicIds,int upOption) throws Exception{
		String sql = "update him_forum_topic set displayorder = ? where topicId = ?";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for(String topicId:topicIds){
			Object[] args = new Object[]{upOption,topicId};
			batchArgs.add(args);
		}
		this.getJdbcTemplate().batchUpdate(sql, batchArgs);
	}
	
	/**
	 * 批量关闭
	 * @param topicIds
	 * @param closed
	 * @throws Exception
	 */
	public void batchClose(String[] topicIds ,int closed) throws Exception{
		String sql = "update him_forum_topic set closed = ? where topicId = ?";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for(String topicId:topicIds){
			Object[] args = new Object[]{closed,topicId};
			batchArgs.add(args);
		}
		this.getJdbcTemplate().batchUpdate(sql, batchArgs);
	}
	
	/**
	 * 批量删除
	 * @param topicIds
	 * @param delOption
	 * @throws Exception
	 */
	public void batchDelete(String[] topicIds ,int delOption) throws Exception{
		String sql = "delete from him_forum_topic where topicId = ?";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for(String topicId:topicIds){
			Object[] args = new Object[]{topicId};
			batchArgs.add(args);
		}
		this.getJdbcTemplate().batchUpdate(sql, batchArgs);
	}
	
	public void delTopic(long topicId) throws Exception{
		String sql = "delete from him_forum_topic where topicId = ?";
		this.getJdbcTemplate().update(sql, new Object[]{topicId});
	}
	
	/**
	 * 批量设置精华
	 * @param topics
	 * @param upOption
	 * @throws Exception
	 */
	public void batchSetTopicDigest(String[] topicIds,int digestOption) throws Exception{
		String sql = "update him_forum_topic set digest = ? where topicId = ?";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for(String topicId:topicIds){
			Object[] args = new Object[]{digestOption,topicId};
			batchArgs.add(args);
		}
		this.getJdbcTemplate().batchUpdate(sql, batchArgs);
	}
	
	public void setViews(long views,long topicId) throws Exception{
		String sql = "update him_forum_topic set views = ? where topicId = ?";
		this.commonUpdate(sql, views,topicId);
	}
	
	public Topic getById(long topicId) throws Exception{
		String sql = "select * from him_forum_topic where topicId = ?";
		return getJavaBean(sql, Topic.class, topicId);
	}
	
	public long getPraiseCount(long rentId) throws Exception{
		String sql = "select praiseCount from him_forum_topic where topicId = ?";
		return this.getJdbcTemplate().queryForLong(sql,rentId);
	}
	
	public long getCommentCount(long rentId) throws Exception{
		String sql = "select commentCount from him_forum_topic where topicId = ?";
		return this.getJdbcTemplate().queryForLong(sql,rentId);
	}
	
	public void addPraiseCount(long infoId) throws Exception {
		String sql = "update him_forum_topic set praiseCount = praiseCount + 1 where topicId = ?";
		this.commonUpdate(sql, infoId);
	}
	
	public void addCommentCount(long infoId) throws Exception {
		String sql = "update him_forum_topic set commentCount = commentCount + 1 where topicId = ?";
		this.commonUpdate(sql, infoId);
	}
	
	public void addReplyCount(long infoId) throws Exception {
		String sql = "update him_forum_topic set replies = replies + 1 where topicId = ?";
		this.commonUpdate(sql, infoId);
	}
	
	/**
	 * 我发表的主题列表统计（客户端功能）
	 * @param model
	 * @param authorId
	 * @return
	 * @throws Exception
	 */
	public int getMyTopicsCount(long userId){
		String sql = "select count(*) from him_forum_topic where authorId="+userId;
		return getCount(sql);
	}
}
